import {
	getMemberInfo,
	login,
	logout
} from '@/api/member';
import {
	getToken,
	setToken,
	removeToken
} from '@/utils/auth'


const state = {
	token: getToken(),
	memberNum: ''
};

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token;
	},

	SET_MEMBER_NUM: (state, memberNum) => {
		state.memberNum = memberNum
	}
};

const actions = {
	Login({
		commit
	}, userInfo) {
		const memberNum = userInfo.memberNum;
		const password = userInfo.password;
		const code = userInfo.code;
		const uuid = userInfo.uuid;
		const loginType = userInfo.loginType;
		return new Promise((resolve, reject) => {
			login(memberNum, password, code, uuid, loginType).then(res => {
				let data = res.data;

				// 设置令牌：因为后端写的是自动刷新缓存，所以这里采用直接存cookie7天
				setToken(data.access_token, 7);
				commit('SET_TOKEN', data.access_token);
				resolve();
			}).catch(error => {
				reject(error);
			});
		});
	},

	GetMemberInfo({
		commit
	}) {
		return new Promise((resolve, reject) => {
			getMemberInfo().then(res => {
				commit('SET_MEMBER_NUM', res.data)
				resolve(res)
			}).catch(error => {
				reject(error)
			})
		})
	},

	LogOut({
		commit,
		state
	}) {
		return new Promise((resolve, reject) => {
			logout(state.token).then(() => {
				commit('SET_TOKEN', '')
				commit('SET_MEMBER_NUM', '')
				removeToken()
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	}
};

const getters = {};

export default {
	state,
	mutations,
	actions,
	getters
}
